//
//  WLCommonTool.m
//  WanLian
//
//  Created by muzhuang on 2018/9/10.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLCommonTool.h"
#import "WLloginController.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import "WLVersionUpdateView.h"
#import "AppDelegate.h"
#import "WLRouterBingFlowController.h"
#import "WLUseManager.h"
#import "WLCloudController.h"

NSString* const FILE_SOCKET_HOST_ROUTER = @"192.168.188.1";
//NSString* const FILE_SOCKET_HOST_ROUTER = @"192.168.188.154";
NSString* const FILE_SOCKET_HOST_REMOTE = @"61.153.186.12";
//NSString* const FILE_SOCKET_HOST_REMOTE = @"192.168.188.154";

NSString* const HTTP_HOST_ROUTER = @"http://192.168.188.1";
//NSString* const HTTP_HOST_ROUTER = @"http://192.168.188.1";
//NSString* const HTTP_HOST_ROUTER = @"http://192.168.188.152";
//NSString* const HTTP_HOST_REMOTE = @"http://192.168.188.1";
NSString* const HTTP_HOST_REMOTE = @"https://www.zeerong.com/router/upload";
NSString* const HTTP_HOST_WEB = @"https://www.zeerong.com/router/web";

@implementation WLCommonTool
+ (NSString *)getWebHost {
    
    return @"https://www.zeerong.com";
}
#pragma mark - 判断
+ (NSString *)formateURLString:(NSString *)urlStr
{
    /*! ios9适配的话 打开第一个 */
    if ([[UIDevice currentDevice] systemVersion].floatValue >= 9.0)
    {
        return [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    }
    else if(IS_SYSTEM_BEYOND_IOS8)
    {
        return [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    return urlStr;
}
+ (BOOL)isConnectionAvailable
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
//    WLLog(@"\n\n网络状态%ld\n\n",(long)manager.networkReachabilityStatus);
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable)
    {
        return NO;
    }
    return YES;
}
+ (BOOL)isConnectWIFI
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //    WLLog(@"\n\n网络状态%ld\n\n",(long)manager.networkReachabilityStatus);
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi)
    {
        return YES;
    }
    return NO;
}
+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    NSString *MOBILE = @"^1[0-9]{10}$";
    //    NSString *MOBILE = @"^((13[0-9])|(14[5,7])|(15[^4,\\D])|(17[0,6-8])|(18[0-9]))\\d{8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    if ([regextestmobile evaluateWithObject:mobileNum] == YES)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+ (BOOL)isValidateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
    
    return [emailTest evaluateWithObject:email];
}

+ (BOOL)isIPAddress:(NSString *)strIP
{
    NSString *pattern = @"(2(5[0-5]{1}|[0-4]\\d{1})|[0-1]?\\d{1,2})(\\.(2(5[0-5]{1}|[0-4]\\d{1})|[0-1]?\\d{1,2})){3}";
    NSPredicate *ipAddress = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",pattern];
    
    return [ipAddress evaluateWithObject:strIP];
//    NSError *error = NULL;
//    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern: pattern options:nil error:&error];
//    NSArray *match = [regex matchesInString:str options:NSMatchingCompleted range:NSMakeRange(0, [str length])];
//    if (match.count != 0) {
//        // ...
//    }
}

+ (NSString *)strAddBlankFormatter:(NSString *)originStr
{
    NSString *newString = [originStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSMutableString *mStr = [NSMutableString stringWithString:newString];
    if (mStr.length >4) {
        [mStr insertString:@" " atIndex:4];
    }
    if (mStr.length > 9) {
        [mStr insertString:@" " atIndex:9];
    }
    if (mStr.length > 14) {
        [mStr insertString:@" " atIndex:14];
    }
    if (mStr.length > 19) {
        [mStr insertString:@" " atIndex:19];
    }
    return  mStr;
}

#pragma mark - 字体
+ (UIFont *)fontTypePingFangSCRegular:(CGFloat)fontSize
{
    if (@available(iOS 9.0, *))
    {
        return [UIFont fontWithName:@"PingFangSC-Regular" size:fontSize];
    }
    return [UIFont systemFontOfSize:fontSize];
}

+ (UIFont *)fontTypePingFangSCMedium:(CGFloat)fontSize
{
    if (@available(iOS 9.0, *))
    {
        return [UIFont fontWithName:@"PingFangSC-Medium" size:fontSize];
    }
    return [UIFont boldSystemFontOfSize:fontSize];
}

+ (UIFont *)fontTypePingFangSCSemibold:(CGFloat)fontSize
{
    if (@available(iOS 9.0, *))
    {
        return [UIFont fontWithName:@"PingFangSC-Semibold" size:fontSize];
    }
    return [UIFont boldSystemFontOfSize:fontSize];
}

#pragma mark 获取Wifi信息
+ (id)fetchSSIDInfo
{
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    id info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        
        if (info && [info count]) {
            break;
        }
    }
    return info;
}
+ (NSString *)getCHeckedWifiBSSID {
    NSString *oriBSSID = [self getWifiBSSID];
    if (oriBSSID.length == 17) {
        return oriBSSID;
    } else if (oriBSSID.length > 0){
        NSMutableString *muStr = [[NSMutableString alloc]initWithCapacity:17];
        NSArray *component = [oriBSSID componentsSeparatedByString:@":"];
        for (NSString *sub in component) {
            if (sub.length == 2) {
                [muStr appendString:sub];
                [muStr appendString:@":"];
                continue;
            } else if(sub.length < 2) {
                [muStr appendString:@"0"];
                [muStr appendString:sub];
                [muStr appendString:@":"];
            }
        }
        
        return [muStr substringToIndex:muStr.length -1];
    }
    return nil;
}
+ (NSString *)getWifiSSID
{
    return (NSString *)[self fetchSSIDInfo][@"SSID"];//WiFi名称
}

+ (NSString *)getWifiBSSID
{
    return (NSString *)[self fetchSSIDInfo][@"BSSID"]; //无线网的MAC地址
}

+ (BOOL)isConnectedTianYiLian
{
    NSString *wifiName = [self getCHeckedWifiBSSID];
    NSString *routerMacAddr = [[WLUseManager shareUser] routerModel].macAddress;
    NSString *lastWifi = [[wifiName substringToIndex:wifiName.length - 3] uppercaseString];
    NSString *routerLast = [[routerMacAddr substringToIndex:routerMacAddr.length - 3] uppercaseString];
    lastWifi = [lastWifi stringByReplacingOccurrencesOfString:@":" withString:@""];
    routerLast = [routerLast stringByReplacingOccurrencesOfString:@":" withString:@""];
    if ([lastWifi isEqualToString:routerLast]) {
        return YES;
    } else {
        return NO;
    }
//    if ([wifiName hasPrefix:@"TianYiLian"])//||wifiName==nil
//    {
//        return YES;
//    }
//    return NO;
}
+ (long)getScoketPort {
    return 9002;
}
+ (NSString *)getHost {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN)//如果是蜂窝网
    {
        return HTTP_HOST_REMOTE;
    } else {
        NSString *routerMacAddr = [[WLUseManager shareUser] routerModel].macAddress;
        if (routerMacAddr == nil) {
#warning
            return @"";
//            return @"http://192.168.188.1";
        }
        return [self isConnectedTianYiLian] ? HTTP_HOST_ROUTER : HTTP_HOST_REMOTE;
    }
}

+ (NSString *)getFileUpDownloadHost {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN)//如果是蜂窝网
    {
        return FILE_SOCKET_HOST_REMOTE;
    } else {
        NSString *routerMacAddr = [[WLUseManager shareUser] routerModel].macAddress;
        if (routerMacAddr == nil) {
#warning
            return @"";
            //            return @"http://192.168.188.1";
        }
        return [self isConnectedTianYiLian] ? FILE_SOCKET_HOST_ROUTER : FILE_SOCKET_HOST_REMOTE;
    }
}
+ (NSString *)getUploadFilePath
{
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path=[docPath stringByAppendingPathComponent:@"uploads"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:path])
    {
        NSError *error;
        [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
    }
    return path;
}

+ (NSString *)getDownloadFilePath
{
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path=[docPath stringByAppendingPathComponent:@"downloads"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:path])
    {
        NSError *error;
        [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
    }
    return path;
}

#pragma mark - 图片、颜色
+ (UIImage*)createImageWithColor:(UIColor*)color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    if (!color || size.width <= 0 || size.height <= 0) return nil;
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+ (UIImage *)gradientColorImageSize:(CGSize)imgSize
{
    NSArray *ar = @[(__bridge id)wlblueColor.CGColor, (__bridge id)wlUIColorRGB(0x2292F5).CGColor];
    UIGraphicsBeginImageContextWithOptions(imgSize, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorGetColorSpace(wlUIColorRGB(0x2292F5).CGColor);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);
    CGPoint start = CGPointMake(0.0, 0.0);
    CGPoint end = CGPointMake(imgSize.width, 0.0);
    CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
//    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    return image;
}

+ (void)addGradientColor:(UIView *)currentView fromColor:(UIColor *)startColor toColor:(UIColor *)endColor
{
    NSArray *arrLayers = [NSArray arrayWithArray:currentView.layer.sublayers];
    for (CALayer *subLayer in arrLayers) {
        if ([subLayer isKindOfClass:[CAGradientLayer class]])
        {
            [subLayer removeFromSuperlayer];
        }
    }
    //    CAGradientLayer类对其绘制渐变背景颜色、填充层的形状(包括圆角)
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = currentView.bounds;
    //  创建渐变色数组，需要转换为CGColor颜色
    gradientLayer.colors = @[(__bridge id)startColor.CGColor,(__bridge id)endColor.CGColor];
    //  设置渐变颜色方向，左上点为(0,0), 右下点为(1,1)
    gradientLayer.startPoint = CGPointMake(0, 0.5);
    gradientLayer.endPoint = CGPointMake(1, 0.5);
    //  设置颜色变化点，取值范围 0.0~1.0
//    gradientLayer.locations = @[@0,@1];
    [currentView.layer insertSublayer:gradientLayer atIndex:0];
}

#pragma mark - Date
+ (NSString *)timeFormatted:(long long)totalSeconds
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970: totalSeconds/1000];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *dateStr = [dateFormat stringFromDate: date];
    return dateStr;
}

+ (NSString *)timeNoHMS:(long long)totalSeconds
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970: totalSeconds/1000];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr = [dateFormat stringFromDate: date];
    return dateStr;
}

+ (NSString *)timeToYMDHMS:(long long)totalSeconds
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970: totalSeconds/1000];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy.MM.dd HH:mm"];
    NSString *dateStr = [dateFormat stringFromDate: date];
    return dateStr;
}

+ (NSString *)timeToSlantYMDHMS:(long long)totalSeconds
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970: totalSeconds/1000];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy/MM/dd HH:mm"];
    NSString *dateStr = [dateFormat stringFromDate: date];
    return dateStr;
}

+ (NSString *)timeIntervalDescription:(NSTimeInterval)timeSeconds
{
    NSDate *dateTime = [NSDate dateWithTimeIntervalSince1970: timeSeconds/1000];
    NSTimeInterval timeInterval = -[dateTime timeIntervalSinceNow];
    if (timeInterval < 60) {
        return [NSString stringWithFormat:@"1分钟内"];
    } else if (timeInterval < 3600) {
        return [NSString stringWithFormat:@"%.f分钟前",timeInterval / 60];
    }
    else if (timeInterval < 28800)//86400
    {
        return [NSString stringWithFormat:@"%.f小时前",timeInterval / 3600];
    }
    else
    {
        NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"YYYY-MM-dd"];
        NSString * dateNow = [formatter stringFromDate:[NSDate date]];
        NSDateComponents *components = [[NSDateComponents alloc] init];
        [components setDay:[[dateNow substringWithRange:NSMakeRange(8,2)] intValue]];
        [components setMonth:[[dateNow substringWithRange:NSMakeRange(5,2)] intValue]];
        [components setYear:[[dateNow substringWithRange:NSMakeRange(0,4)] intValue]];
        NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        NSDate *date = [gregorian dateFromComponents:components];
        
//        NSInteger hour = [self hoursAfterDate:date];
        NSTimeInterval ti = [dateTime timeIntervalSinceDate:date];
        NSInteger hour = (NSInteger) (ti / 3600);
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        NSString *ret = @"";
        
        //If hasAMPM==TURE, use 12-hour clock, otherwise use 24-hour clock
        NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
        NSRange containsA = [formatStringForHours rangeOfString:@"a"];
        BOOL hasAMPM = containsA.location != NSNotFound;
        
        if (!hasAMPM) { //24-hour clock
            if (hour <= 24 && hour >= 0) {
                dateFormatter.dateFormat = @"HH:mm";
            }else if (hour < 0 && hour >= -24) {
                dateFormatter.dateFormat = @"昨天HH:MM";
            }else {
                dateFormatter.dateFormat = @"yyyy/MM/dd HH:mm";
            }
        }else {
            if (hour >= 0 && hour <= 6) {
                dateFormatter.dateFormat = @"凌晨hh:mm";
            }else if (hour > 6 && hour <=11 ) {
                dateFormatter.dateFormat = @"上午hh:mm";
            }else if (hour > 11 && hour <= 17) {
                dateFormatter.dateFormat = @"下午hh:mm";
            }else if (hour > 17 && hour <= 24) {
                dateFormatter.dateFormat = @"晚上hh:mm";
            }else if (hour < 0 && hour >= -24){
                dateFormatter.dateFormat = @"昨天HH:mm";
            }else  {
                dateFormatter.dateFormat = @"yyyy/MM/dd HH:mm";
            }
        }
        
        ret = [dateFormatter stringFromDate:dateTime];
        return ret;
    }
}

+ (NSString *)strToLoginTime:(long)time
{
    NSString *strTime = @"";
    if (time<60) {
        strTime = [NSString stringWithFormat:@"%ld秒",time];
    }
    else if (time<3600)
    {
        strTime = [NSString stringWithFormat:@"%ld分钟",time/60];
    }
    else if (time<86400)
    {
        strTime = [NSString stringWithFormat:@"%ld小时",time/3600];
    }
    else
    {
        strTime = [NSString stringWithFormat:@"%ld天",time/86400];
    }
//    //return days + "天" + hours + "小时" + minutes + "分" + second + "秒";
//    if(days>0){
//        time+=days + "天";
//    }
//    if(hours>0){
//        time+=hours + "小时";
//    }
//    if(minutes>0){
//        time+=minutes + "分";
//    }
//    if(second>0){
//        time+=second + "秒";
//    }
    return strTime;
}

+ (NSString *)mStorageChangeToStr:(CGFloat)fileSize
{
    if (fileSize<1024) {
        return [NSString stringWithFormat:@"%.2fM", fileSize];
    }
    else
    {
        return [NSString stringWithFormat:@"%.2fG", fileSize/1024.0];
    }
//    else if (fileSize<1024*1024)
//    {
//        return [NSString stringWithFormat:@"%.2fG", fileSize/1024];
//    }
//    else if (fileSize<)
}

+ (void)goToLogin
{
#warning
//    return;
    [[WLSocketManager sharedSocketManager] userManualdisconnect];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:USER_SESSION] !=nil)
    {
//        [self userLogout];
        WLloginController *loginController = [[WLloginController alloc] init];
        [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:[[UINavigationController alloc] initWithRootViewController:loginController] animated: NO completion:nil];
        [WLCommonTool userLogout];
    }
}
+ (void)fourceGoToLogin
{
    [[WLSocketManager sharedSocketManager] userManualdisconnect];
        //        [self userLogout];
    WLloginController *loginController = [[WLloginController alloc] init];
    [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:[[UINavigationController alloc] initWithRootViewController:loginController] animated:YES completion:nil];
    [WLCommonTool userLogout];
}
+ (void)userLogout
{
    [[WLSocketManager sharedSocketManager] userManualdisconnect];
    [[WLUseManager shareUser] clearUserInfo];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults removeObjectForKey:USER_SESSION];
    [userDefaults removeObjectForKey:UNREAD_MSG_NUM];
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UITabBarController *mainVC = (UITabBarController *)appDelegate.wlTabbarController;
    UINavigationController *indexVC = (UINavigationController *)mainVC.selectedViewController;
    [indexVC.navigationController popToRootViewControllerAnimated:NO];
    mainVC.selectedIndex = 0;
}

+ (void)showAlrtToSettingWithTitle:(NSString *)title message:(NSString *)message cancel:(NSString *)cancelStr confirmStr:(NSString *)confirmStr
{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:cancelStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self popToHomeViewController];
    }];
    [alert addAction:cancelAction];
    
    UIAlertAction * setAction = [UIAlertAction actionWithTitle:confirmStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSURL *url = nil;
            if (@available(iOS 10.0, *)) {
                url = [NSURL URLWithString:@"App-Prefs:root=WIFI"];
            } else {
               url = [NSURL URLWithString:@"prefs:root=WIFI"];

            }
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
            }
            [self popToHomeViewController];
        });
        
    }];
    
    [alert addAction:setAction];
    
    [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:alert animated:YES completion:nil];
}

+ (void)popToHomeViewController  {
    UINavigationController *indexVC = [self getHomeNavigationController];
    if (indexVC.childViewControllers.count > 1) {
        [indexVC popToRootViewControllerAnimated:NO];
    }
}
+ (UINavigationController *)getHomeNavigationController {
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UITabBarController *mainVC = (UITabBarController *)appDelegate.wlTabbarController;
    UINavigationController *homeIndexVC = (UINavigationController *)mainVC.viewControllers.firstObject;
    return homeIndexVC;
}
+ (BOOL)judgeNeedShowSettingAlert {
    UINavigationController *indexVC = [self getHomeNavigationController];
    for (UIViewController *subVC in indexVC.childViewControllers) {
        if ([subVC isKindOfClass:[WLCloudController class]]) {
            return YES;
        }
    }
    return NO;
}
+ (void)versionUpdateCheck
{
    NSDictionary *paramsp = @{@"ckey":@"APP_VERSION_IOS"};
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"config/getconfigbykey" withParamsDic:paramsp success:^(NSDictionary *successDict) {
        NSString *strVersion = successDict[@"versionCode"];
        //获取当前版本
        NSString *currentVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
        if ([strVersion floatValue]>currentVersion.floatValue)
        {
            WLVersionUpdateView *updateView = [[WLVersionUpdateView alloc] initWithInfo:successDict[@"object"]];
            [updateView show];
        }
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        
    } error:^(NSError *error) {
        
    } inView:nil];
}

+ (void)pushToBingFlowController//:(NSString *)classStr
{
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UITabBarController *mainVC = (UITabBarController *)appDelegate.wlTabbarController;
    UINavigationController *indexVC = (UINavigationController *)mainVC.selectedViewController;
    WLRouterBingFlowController *viewController = [[WLRouterBingFlowController alloc] init];
    viewController.flowStatus = 1;
//    WLBaseVController *viewController = [[NSClassFromString(classStr) alloc] init];
    if (indexVC.viewControllers.count<=1) {
        viewController.hidesBottomBarWhenPushed = YES;
    }
    [indexVC pushViewController:viewController animated:NO];
}

+ (void)queryUserInfo
{
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"user/app/query" withParamsDic:nil success:^(NSDictionary *successDict) {
        WLUserInfo *user = [WLUserInfo mj_objectWithKeyValues:successDict[@"object"]];
        [[WLUseManager shareUser] updateUserValue:user];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        
    } error:^(NSError *error) {
        
    } inView:nil];
}

+ (NSString *)getRealURLWithUrlStr:(NSString *)url {
    return [NSString stringWithFormat:@"%@%@", [self getHost], url];
}
/**
 * 验证是否为钱包地址
 * 0x开头
 * 40位16进制
 */
+ (BOOL)evalueateETCWalletAccount:(NSString *)accountStr {
//    accountStr = @"0x50353287e8E24E78cC8Dd7e4bb5eCc18319f5F98";
    if (accountStr == nil || [accountStr isEqualToString:@""] || [accountStr length] != 42) {
        [SVProgressHUD showAndAutoCloseWithStatus:@"账户地址长度为42位，请重新输入" delayTime:2.f];
        return NO;
    }
    if (![[accountStr substringWithRange:NSMakeRange(0, 2)] isEqualToString:@"0x"]) {
        [SVProgressHUD showAndAutoCloseWithStatus:@"账户地址需要以0x开头，请重新输入" delayTime:2.f];
        return NO;
    }
    NSString * regex = @"^[A-Fa-f0-9]{40}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    NSString *subSt = [accountStr substringFromIndex:2];
    if (![predicate evaluateWithObject:subSt]) {
        [SVProgressHUD showAndAutoCloseWithStatus:@"账户地址后40位由16进制大写霍骁字母及数字组成，请重新输入" delayTime:2.f];
        return NO;
    }
    return YES;
}

/**
 * 验证是否为INT账户地址
 * 35位以上的INT账户地址
 * 35位16进制
 */
+ (BOOL)evalueateINTAccount:(NSString *)accountStr {
        accountStr = @"iekdiejdufudjsusjduejduejduejduejdu";
    if (accountStr == nil || [accountStr isEqualToString:@""]) {
        [SVProgressHUD showAndAutoCloseWithStatus:@"正确的INT账户地址有35~37位的大小写及数字组成，请重新输入" delayTime:2.f];
        return NO;
    }

    NSString * regex = @"^[A-Za-z0-9]{35,37}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
//    NSString *subSt = [accountStr substringFromIndex:2];
    if (![predicate evaluateWithObject:accountStr]) {
        [SVProgressHUD showAndAutoCloseWithStatus:@"正确的INT账户地址有35~37位的大小写及数字组成，请重新输入" delayTime:2.f];
        return NO;
    }
    return YES;
}

+(NSMutableAttributedString *)getINTDescriptionWithINTNum:(NSString *)INTScore {
    NSString *strTip = @"";
    if (INTScore !=nil && [INTScore isKindOfClass:[NSNull class]]==NO) {
        strTip = [NSString stringWithFormat:@"您当前可兑换的积分额度为：%@积分",INTScore];
    }
    else
    {
        strTip = @"您当前可兑换的积分额度为：0.000000积分";
    }
    
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:strTip];
    [attStr addAttribute:NSForegroundColorAttributeName value:wlblueColor range:NSMakeRange(13, attStr.length-15)];
    return attStr;
}
+ (NSString *)getAppVersion {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
//    // app名称
//    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
//    // app build版本
//    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    return app_Version;
}
@end
